package com.kpx.app.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Poi;
import com.amap.api.maps.overlay.BusRouteOverlay;
import com.amap.api.maps.overlay.DrivingRouteOverlay;
import com.amap.api.maps.overlay.WalkRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.geocoder.RegeocodeRoad;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.road.Crossroad;
import com.amap.api.services.route.BusPath;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.andview.refreshview.XRefreshView;
import com.kpx.app.R;
import com.kpx.app.adapter.ChoiceLocationAdapter;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.LocationDetails;
import com.kpx.app.listener.OnLocationReceivedListener;
import com.kpx.app.thirdparty.amap.LocationGetter;
import com.kpx.app.utils.StringUtil;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.datautils.LogUtils;
import com.kpx.app.utils.uiutils.MapUtils;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class ActivityMap extends ActivityBase implements PoiSearch.OnPoiSearchListener, GeocodeSearch.OnGeocodeSearchListener, AMap.OnCameraChangeListener, OnLocationReceivedListener, LocationSource, RouteSearch.OnRouteSearchListener, AMap.OnPOIClickListener {
    public static final String BAIDUMAP_CONFIG = "baiduMapConfig";
    public static final String LOCATION_RESULT_KEY = "locationResult";
    private static final String TAG = ActivityMap.class.getName();
    int keywordsIndex = 0;
    private MapView mapView;
    private AMap baiduMap;
    private TextView locationView;
    private LocationDetails locationResult;
    private double latitude;
    private double longitude;
    private double myLat;
    private double myLon;
    private int pageIndex = 0;
    private PoiSearch poiSearch;
    private String keyWord = "";
    private boolean doRefreshing;
    private View currentChoosedMarkView;
    private int currentChoosedPosition = -1;
    private boolean validateStatus;
    private boolean isLoading;
    private boolean isDestroyed;
    private String[] keywords = {"街道", "大厦", "美食", "酒店", "小区", "景点"};
    private boolean searchNearby = true;
    private LocationGetter locationGetter;
    private float zoom = 15;
    // 初始化全局 bitmap 信息，不用时及时 recycle
    private BitmapDescriptor otherBD = BitmapDescriptorFactory.fromResource(R.drawable.dt_03_big);
    private BitmapDescriptor myBD = BitmapDescriptorFactory.fromResource(R.drawable.dt_06_big);
    private BaiduMapConfig baiduMapConfig;
    /**
     * 位置改变监听
     */
    private LocationSource.OnLocationChangedListener mListener;
    /**
     * 自定义定位小蓝点
     */
    private MyLocationStyle myLocationStyle;
    /**
     * 地图工具栏返回按钮
     */
    private TextView mTvBackBtn;
    /**
     * 我的位置
     */
    private LatLng mMyLatLng;
    /**
     * 商户位置
     */
    private LatLng mOtherLatLng;
    /**
     * 选中的周边列表的某一个地址
     */
    private String mChooseListAddress;
    /**
     * 选中的详细地址
     */
    private String mChooseDetailAddress;
    /**
     * 当前位置选中时的效果
     */
    private ImageView mCurrentLocationImageView;

    private View mapViewContainer;

    private View locationDisableView;
    private XRefreshView xRefView;
    private ArrayList<PoiItem> poiItems;
    private ChoiceLocationAdapter adapter;
    private TitleView titleView;

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
    public void getLocationPermission() {
        showLocationDisableView();
        getLocation();
    }

    private void getLocation() {
        if (null == locationGetter) {
            locationGetter = new LocationGetter(ActivityMap.this, this);
        }
        if (MapUtils.isLocationAccessable(this)) {
            locationGetter.getLocation();
        }
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
    public void showRationaleForLocation(final PermissionRequest request) {
        request.proceed();
//        activityBase.showYesNoDialog(getString(R.string.setting), getString(R.string.cancel), getString(R.string.alert_location_permission), new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                switch (which) {
//                    case DialogInterface.BUTTON_POSITIVE:
//                        request.proceed();
//                        break;
//                }
//            }
//        });
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
    public void onLocationDenied() {
        ToastUtil.getInstance().showDialog(this, getString(R.string.denied_location_permission));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        ActivityMapPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    private void showLocationDisableView() {
        if (MapUtils.isLocationAccessable(this)) {
            mapViewContainer.setVisibility(View.VISIBLE);
            locationDisableView.setVisibility(View.GONE);
        } else {
            mapViewContainer.setVisibility(View.GONE);
            locationDisableView.setVisibility(View.VISIBLE);
            View openGPSBtn = findViewById(R.id.openGPSBtn);
            openGPSBtn.setVisibility(View.VISIBLE);
            openGPSBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    } catch (Exception e) {
                        ToastUtil.getInstance().showToast(ActivityMap.this, "启动地理位置设置页面失败，请您到设置页面手动开启");
                    }
                }
            });
        }
        if (baiduMapConfig != null) {
            if (!baiduMapConfig.enableSearch) {
                findViewById(R.id.mapSearchNearbyContainer).setVisibility(View.GONE);
            }
        }
    }

    private int getZoom(float distance) {
        Map<Integer, Integer> scaleControls = new HashMap<>();
        scaleControls.put(2, 20);
        scaleControls.put(5, 19);
        scaleControls.put(12, 18);
        scaleControls.put(25, 17);
        scaleControls.put(50, 16);
        scaleControls.put(100, 15);
        scaleControls.put(250, 14);
        scaleControls.put(500, 13);
        scaleControls.put(1000, 12);
        scaleControls.put(2000, 11);
        scaleControls.put(5000, 10);
        scaleControls.put(10000, 9);
        scaleControls.put(15000, 8);
        scaleControls.put(25000, 7);
        scaleControls.put(50000, 6);
        scaleControls.put(100000, 5);
        scaleControls.put(250000, 4);
        scaleControls.put(500000, 3);
        List<Integer> keys = new ArrayList<>();
        Set<Integer> integers = scaleControls.keySet();
        for (Integer unit : integers) {
            keys.add(unit);
        }
        Collections.sort(keys);
        for (Integer unit : keys) {
            if (distance / 4 <= unit) {
                return scaleControls.get(unit);
            }
        }
        return 20;
    }

    /**
     * 同时显示我的定位信息和其他位置
     */
    private void showMyAndOtherLocation(final LatLng myLatLng, final LatLng otherLatLng) {
        if (isDestroyed) {
            return;
        }
        if (baiduMapConfig != null && baiduMapConfig.showOtherLocation) {
            MarkerOptions otherOO = new MarkerOptions().anchor(0.5f, 0.5f).position(otherLatLng).icon(otherBD).draggable(false).title("商家位置");
            baiduMap.addMarker(otherOO);
            TextView distanceView = (TextView) findViewById(R.id.distanceView);
            distanceView.setVisibility(View.GONE);
            if (baiduMapConfig.showDistance) {
                locationView.setVisibility(View.GONE);
                findViewById(R.id.markView).setVisibility(View.GONE);
                MarkerOptions myOO = new MarkerOptions().anchor(0.5f, 0.5f).position(myLatLng).icon(myBD).draggable(false).title("我的位置");
                baiduMap.addMarker(myOO);
                float lineDistance = AMapUtils.calculateLineDistance(myLatLng, otherLatLng);
                zoom = getZoom(lineDistance);
                String s = StringUtil.m2KM(lineDistance);
                distanceView.setVisibility(View.VISIBLE);
                distanceView.setText("两地相距" + s);

                mMyLatLng = myLatLng;
                mOtherLatLng = otherLatLng;
            } else {
                zoom = 15;
            }
        }
        LogUtils.i(TAG, "我的定位信息： " + myLatLng);
        setBaiduMapCenter(myLatLng.latitude, myLatLng.longitude);
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        if (null != locationGetter) {
            locationGetter.stopLocation();
        }
    }

    @Override
    public void onLocationReceived(final LocationDetails locationDetails, boolean isOverAgain, AMapLocation amapLocation) {
        if (isOverAgain) {
            LogUtils.d(TAG, "获取到了定位信息： " + amapLocation);
            if (null == amapLocation && null != locationGetter) {
                locationGetter.getLocation();
                LogUtils.d(TAG, "onLocationReceived() 获取到地理位置信息为空");
            } else {
                if (mListener != null && amapLocation != null) {
                    if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                        mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                    }
                }
            }
            return;
        }
        LogUtils.d(TAG, "获取到了定位信息： " + locationDetails);
        if (null == locationGetter) {
            return;
        }
        locationGetter.stopLocation();
        //TODO 获取到定位信息之后的操作
        if (locationDetails == null) {
            locationGetter.getLocation();
            LogUtils.d(TAG, "onLocationReceived() 获取到地理位置信息为空");
        } else {
            final LocationDetails myLocation = locationDetails;
            if (myLat == 0) {
                myLat = myLocation.getLatitude();
                myLon = myLocation.getLongitude();
            }
            View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LogUtils.d(TAG, "回到原来的位置..." + myLocation.latitude + "  " + myLocation.longitude);
                    if (currentChoosedMarkView != null) {
                        currentChoosedPosition = -1;
                        currentChoosedMarkView.setVisibility(View.INVISIBLE);
                        currentChoosedMarkView = null;
                    }
                    setBaiduMapCenter(myLat, myLon);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (mCurrentLocationImageView != null) {
                                mCurrentLocationImageView.setVisibility(View.VISIBLE);
                            }
                            mChooseDetailAddress = null;
                        }
                    }, 600);
                }
            };
            ((TextView) findViewById(R.id.currentSelectView)).setText(locationDetails.getAddrStr());
            findViewById(R.id.curSelectedContainer).setOnClickListener(onClickListener);
            mCurrentLocationImageView = (ImageView) findViewById(R.id.choosedImageView);
            View locatieMyPositionView = findViewById(R.id.locatieMyPositionView);
            locatieMyPositionView.setVisibility(View.VISIBLE);
            locatieMyPositionView.setOnClickListener(onClickListener);
            LogUtils.d(TAG, "onLocationReceived() 获取当前的定位信息……" + myLocation);
            LatLng myLatLng = null;
            LatLng otherLatLng = null;
            if (baiduMapConfig != null) {
                if (baiduMapConfig.showMyLocation) {
                    LocationDetails presetMyLocation = baiduMapConfig.presetMyLocation;
                    if (presetMyLocation != null && presetMyLocation.latitude != 0) {
                        LogUtils.d(TAG, "onLocationReceived() 使用预设的我的定位信息……" + presetMyLocation);
                        myLatLng = new LatLng(presetMyLocation.latitude, presetMyLocation.longitude);
                        locationResult = presetMyLocation;
                    } else {
                        LogUtils.d(TAG, "onLocationReceived() 使用当前的定位信息……" + myLocation);
                        myLatLng = new LatLng(myLocation.latitude, myLocation.longitude);
                        locationResult = myLocation;
                    }
                }
                boolean showOtherLocation = baiduMapConfig.showOtherLocation;
                if (showOtherLocation) {
                    LocationDetails otherLocation = baiduMapConfig.otherLocation;
                    if (otherLocation != null && otherLocation.latitude != 0) {
                        LogUtils.d(TAG, "onLocationReceived() 显示其他定位信息……" + otherLocation);
                        otherLatLng = new LatLng(otherLocation.latitude, otherLocation.longitude);
                    } else {
                        LogUtils.d(TAG, "onLocationReceived() 传入的 其他定位信息有误……");
                    }
                }
                if (baiduMapConfig.enableSearch) {
                    if (keywordsIndex >= keywords.length) {
                        return;
                    }
                    LogUtils.d(TAG, "获取到定位信息。。。。搜索附近地址");
                    keyWord = keywords[keywordsIndex];
                    pageIndex = 0;
                    latitude = myLatLng.latitude;
                    longitude = myLatLng.longitude;
                    searchNearby();
                }
                showMyAndOtherLocation(myLatLng, otherLatLng);
            }
        }
    }

    private void setBaiduMapCenter(double lat, double lon) {
        this.latitude = lat;
        this.longitude = lon;
        baiduMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), zoom), 500, null);
        locationGetter.geocodeToAddress(new LatLonPoint(latitude, longitude), this);
        LogUtils.i(TAG, "当前中心点位置： " + latitude + "  " + longitude);
    }

    private void setResultAndFinish() {
        final Intent intent = new Intent();
        if (null != baiduMapConfig && baiduMapConfig.needLocationBack) {
            boolean hasLocationResult = true;
            String message;
            if (locationResult != null && MapUtils.isValidateLatitude(locationResult.latitude) && MapUtils.isValidateLogitude(locationResult.longitude)) {
                if (!TextUtils.isEmpty(mChooseListAddress)) {
                    locationResult.setAddrStr(mChooseListAddress);
                }
                if (!TextUtils.isEmpty(mChooseDetailAddress)) {
                    locationResult.setDetailAddress(mChooseDetailAddress);
                } else {
                    locationResult.setDetailAddress(null);
                }
                message = "您选择的位置信息为：" + locationResult.getAddrStr() + "。";
                if (StringUtil.isEmpty(locationResult.getAddrStr())) {
                    message = "获取您的位置坐标信息，但是未解析出具体的地理位置。";
                }
            } else {
                hasLocationResult = false;
                message = "位置信息获取失败。";
            }
            final boolean hasResult = hasLocationResult;
            AlertDialog.OnClickListener listener = new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case DialogInterface.BUTTON_POSITIVE:
                            if (hasResult) {
                                intent.putExtra(ActivityMap.LOCATION_RESULT_KEY, locationResult);
                                setResult(Activity.RESULT_OK, intent);
                                finish();
                                overridePendingTransition(R.anim.open_left_in, R.anim.close_right_out);
                            } else {
                                finish();
                                overridePendingTransition(R.anim.open_left_in, R.anim.close_right_out);
                            }
                            dialog.dismiss();
                            break;
                        case DialogInterface.BUTTON_NEGATIVE:
                            dialog.dismiss();
                            finish();
                            break;
                    }
                }
            };
            AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle(R.string.tips).setMessage(message).setPositiveButton(getString(R.string.sure), listener).setNegativeButton(getString(R.string.cancel), listener).create();
            alertDialog.setCanceledOnTouchOutside(false);
            alertDialog.show();
        } else {
            finish();
            overridePendingTransition(R.anim.open_left_in, R.anim.close_right_out);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (null != mapView) {
            mapView.onResume();
        }
        ActivityMapPermissionsDispatcher.getLocationPermissionWithCheck(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (null != mapView) {
            mapView.onPause();
        }
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isDestroyed = true;
        if (otherBD != null) {
            otherBD.recycle();
            otherBD = null;
        }
        if (myBD != null) {
            myBD.recycle();
            myBD = null;
        }
        if (null != mapView) {
            mapView.onDestroy();
        }
        deactivate();
    }

    private void searchNearby() {
        if (!baiduMapConfig.enableSearch) {
            return;
        }
        LinearLayout searchNearbyContainer = (LinearLayout) findViewById(R.id.mapSearchNearbyContainer);
        if (xRefView == null) {
            xRefView = new XRefreshView(this);
            //初始化上下拉刷新view-----------------------------
            xRefView.setPullLoadEnable(true);
            xRefView.setPinnedTime(1000);
            xRefView.setAutoLoadMore(true);
//		outView.setCustomHeaderView(new CustomHeader(this));
//		outView.setCustomHeaderView(new XRefreshViewHeader(this));
            xRefView.setMoveForHorizontal(true);
//        outView.setCustomFooterView(new CustomerFooter(this));
//		outView.setPinnedContent(true);
            ListView listView = new ListView(this);
            poiItems = new ArrayList<>();
            adapter = new ChoiceLocationAdapter(this, poiItems, R.layout.map_search_nearby_view_item);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    validateStatus = false;
                    PoiItem poiItem = poiItems.get(position);
                    LatLonPoint location = poiItem.getLatLonPoint();
                    // 拼接选中列表的某一项展示给用户看
                    String provinceName = poiItem.getProvinceName();
                    provinceName = StringUtil.isEmpty(provinceName) ? "" : provinceName;
                    String cityName = poiItem.getCityName();
                    cityName = StringUtil.isEmpty(cityName) ? "" : cityName;
                    String snippet = poiItem.getSnippet();
                    mChooseListAddress = provinceName + cityName + poiItem.getAdName() + snippet;
                    mChooseDetailAddress = snippet;
                    setBaiduMapCenter(location.getLatitude(), location.getLongitude());
                }
            });
            //商品列表的上下拉刷新操作
            xRefView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
                @Override
                public void onRefresh() {
                    if (isLoading) {
                        return;
                    }
                    isLoading = true;
                    pageIndex = 0;
                    doRefreshing = true;
                    searchNearby();
                }

                @Override
                public void onLoadMore(boolean isSlience) {
                    if (isLoading) {
                        return;
                    }
                    isLoading = true;
                    searchNearby();
                }
            });
            xRefView.addView(listView);
            if (xRefView == null) {
                return;
            }
            xRefView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            searchNearbyContainer.addView(xRefView);
        }
        PoiSearch.Query query = new PoiSearch.Query(keyWord, "", "");
        query.setPageNum(pageIndex);
        query.setPageSize(10);
        try {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);
            if (searchNearby) {
                poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(latitude, longitude), 2000, true));
            }
            poiSearch.searchPOIAsyn();
        } catch (Exception e) {
            LogUtils.e(TAG, e.getMessage());
        }
    }

//    @Override
//    public void onAction(int action, String result) {
//        switch (action) {
//            case ACTION_CLEAR_INPUT:
//                keyWord = keywords[0];
//                searchNearby = true;
//                break;
//            case ACTION_DONE:
//                hideSoftKeyboard();
//                if (StringUtil.isEmpty(result)) {
//                    return;
//                }
//                currentChoosedPosition = -1;
//                currentChoosedMarkView = null;
//                searchNearby = false;
//                pageIndex = 0;
//                keyWord = result;
//                searchNearby();
//                break;
//        }
//    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        searchNearby = true;
        if (null != mCurrentLocationImageView) {
            mCurrentLocationImageView.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        LogUtils.i(TAG, "当前地图的缩放比例：  " + cameraPosition.zoom);
        LatLng target = cameraPosition.target;
        if ((latitude == target.latitude) && (longitude == target.longitude)) {
            return;
        }
        latitude = target.latitude;
        longitude = target.longitude;
        LogUtils.i(TAG, "  onCameraChangeFinish  = " + latitude + "  " + longitude);
        LogUtils.i(TAG, "enableSearch:" + baiduMapConfig.enableSearch + ",isLoading:" + isLoading + ",validateStatus:" + validateStatus);
        if (baiduMapConfig.enableSearch && !isLoading && validateStatus) {
            locationGetter.geocodeToAddress(new LatLonPoint(latitude, longitude), this);
            pageIndex = 0;
            searchNearby();
            LogUtils.i(TAG, " onCameraChangeFinish() : 更新数据……");
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int errorCode) {
        if (regeocodeResult != null && regeocodeResult.getRegeocodeAddress() != null && !StringUtil.isEmpty(regeocodeResult.getRegeocodeAddress().getFormatAddress())) {
            RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
            String address = regeocodeAddress.getFormatAddress();
            LatLonPoint point = regeocodeResult.getRegeocodeQuery().getPoint();
            if (locationResult != null) {
                locationResult.setLatitude(point.getLatitude());
                locationResult.setLongitude(point.getLongitude());
                locationResult.setAddrStr(address);
            }
            String province = regeocodeAddress.getProvince();
            String city = regeocodeAddress.getCity();
            String district = regeocodeAddress.getDistrict();
            String building = regeocodeAddress.getBuilding();
            List<Crossroad> crossroads = regeocodeAddress.getCrossroads();
            String neighborhood = regeocodeAddress.getNeighborhood();
            String township = regeocodeAddress.getTownship();
            List<RegeocodeRoad> roads = regeocodeAddress.getRoads();
            LogUtils.i(TAG, "  地址详情  " + building + "  " + neighborhood + "  " + township + "  " + roads + "  " + crossroads);
            if (locationResult != null) {
                locationResult.setCity(regeocodeAddress.getCity());
                locationResult.setDistrict(regeocodeAddress.getDistrict());
                locationResult.setProvince(regeocodeAddress.getProvince());
            }
            String streetNumber = regeocodeAddress.getStreetNumber().getNumber();
            String street = regeocodeAddress.getStreetNumber().getStreet();
            if (locationResult != null) {
                locationResult.setStreet(StringUtil.isEmpty(street) ? street : address.substring((province + city + district).length()));
                locationResult.setStreetNumber(StringUtil.isEmpty(streetNumber) ? streetNumber : "");
            }
            locationView.setText(address);
            locationView.setVisibility(View.GONE);

            LogUtils.i(TAG, " 地理位置反转……" + point.getLatitude() + "  " + point.getLongitude() + "  结果为： " + locationResult);
        } else {
            locationView.setVisibility(View.GONE);
            LogUtils.i(TAG, " 地理位置反编码错误……");
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        if (poiResult == null) {
            xRefView.setAutoLoadMore(false);
        } else {
            List<PoiItem> allPoi = poiResult.getPois();
            int startPosition;
            doRefreshing = false;
            isLoading = false;
            if (allPoi == null || allPoi.size() == 0) {
                xRefView.setAutoLoadMore(false);
                if (adapter.getDatas().size() > 0) {
                    xRefView.stopRefresh();
                    return;
                }
                if (searchNearby) {
                    if (keywordsIndex < keywords.length) {
                        LogUtils.i(TAG, "搜索到附近，关键字为：" + keyWord);
                        pageIndex = 0;
                        keyWord = keywords[keywordsIndex];
                        searchNearby();
                        keywordsIndex++;
                    }
                }
            } else {
                if (pageIndex == 0) {
                    poiItems.clear();
                    if (currentChoosedMarkView != null) {
                        currentChoosedPosition = -1;
                        currentChoosedMarkView.setVisibility(View.INVISIBLE);
                        currentChoosedMarkView = null;
                    }
                    mChooseListAddress = null;
                    mChooseDetailAddress = null;
                }
                List<PoiItem> emptySnippetsPoi = new ArrayList<>();
                for (int j = 0; j < allPoi.size(); j++) {
                    if (StringUtil.isEmpty(allPoi.get(j).getSnippet())) {
                        emptySnippetsPoi.add(allPoi.get(j));
                    }
                }
                allPoi.removeAll(emptySnippetsPoi);
                xRefView.setAutoLoadMore(true);
                startPosition = adapter.getDatas().size();
                poiItems.addAll(allPoi);
                adapter.notifyDataSetChanged();
                pageIndex++;
            }
        }
        xRefView.stopRefresh();
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }


    /**
     * 公交路线查询回调
     *
     * @param result
     * @param rCode
     */
    @Override
    public void onBusRouteSearched(BusRouteResult result, int rCode) {
        dissmissLoadingDialog();
        if (rCode == 0) {
            if (result != null && result.getPaths() != null && result.getPaths().size() > 0) {
                BusRouteResult busRouteResult = result;
                BusPath busPath = busRouteResult.getPaths().get(0);
                baiduMap.clear();// 清理地图上的所有覆盖物
                BusRouteOverlay routeOverlay = new BusRouteOverlay(this, baiduMap, busPath, busRouteResult.getStartPos(), busRouteResult.getTargetPos());
                routeOverlay.removeFromMap();
                routeOverlay.addToMap();
                routeOverlay.zoomToSpan();
            } else {
                ToastUtil.getInstance().showToast(this, R.string.no_result, Toast.LENGTH_LONG);
            }
            baiduMap.setMyLocationStyle(myLocationStyle);
        } else if (rCode == 27) {
            ToastUtil.getInstance().showToast(this, R.string.error_network, Toast.LENGTH_LONG);
        } else if (rCode == 32) {
            ToastUtil.getInstance().showToast(this, R.string.error_key, Toast.LENGTH_LONG);
        } else {
            ToastUtil.getInstance().showToast(this, R.string.error_other, Toast.LENGTH_LONG);
        }
    }

    /**
     * 驾车结果回调
     *
     * @param result
     * @param rCode
     */
    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
        dissmissLoadingDialog();
        if (rCode == 0) {
            if (result != null && result.getPaths() != null && result.getPaths().size() > 0) {
                DriveRouteResult driveRouteResult = result;
                DrivePath drivePath = driveRouteResult.getPaths().get(0);
                baiduMap.clear();// 清理地图上的所有覆盖物
                DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(this, baiduMap, drivePath, driveRouteResult.getStartPos(), driveRouteResult.getTargetPos());
                drivingRouteOverlay.removeFromMap();
                drivingRouteOverlay.addToMap();
                drivingRouteOverlay.zoomToSpan();
                baiduMap.setMyLocationStyle(myLocationStyle);
            } else {
                ToastUtil.getInstance().showToast(this, R.string.no_result);
            }
        } else if (rCode == 27) {
            ToastUtil.getInstance().showToast(this, R.string.error_network);
        } else if (rCode == 32) {
            ToastUtil.getInstance().showToast(this, R.string.error_key);
        } else {
            ToastUtil.getInstance().showToast(this, R.string.error_other);
        }
    }

    /**
     * 步行路线结果回调
     *
     * @param result
     * @param rCode
     */
    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int rCode) {
        dissmissLoadingDialog();
        if (rCode == 0) {
            if (result != null && result.getPaths() != null && result.getPaths().size() > 0) {
                WalkRouteResult walkRouteResult = result;
                WalkPath walkPath = walkRouteResult.getPaths().get(0);
                baiduMap.clear();// 清理地图上的所有覆盖物
                WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(this, baiduMap, walkPath, walkRouteResult.getStartPos(), walkRouteResult.getTargetPos());
                walkRouteOverlay.removeFromMap();
                walkRouteOverlay.addToMap();
                walkRouteOverlay.zoomToSpan();
                baiduMap.setMyLocationStyle(myLocationStyle);
            } else {
                ToastUtil.getInstance().showToast(this, R.string.no_result);
            }
        } else if (rCode == 27) {
            ToastUtil.getInstance().showToast(this, R.string.error_network);
        } else if (rCode == 32) {
            ToastUtil.getInstance().showToast(this, R.string.error_key);
        } else {
            ToastUtil.getInstance().showToast(this, R.string.error_other);
        }
    }

    @Override
    public void onPOIClick(Poi poi) {
        MarkerOptions markOptiopns = new MarkerOptions();
        markOptiopns.position(poi.getCoordinate());
        TextView textView = new TextView(this);
        textView.setText(poi.getName());
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(Color.BLACK);
        textView.setBackgroundResource(R.drawable.custom_info_bubble);
        markOptiopns.icon(BitmapDescriptorFactory.fromView(textView));
        baiduMap.addMarker(markOptiopns);
    }

    public static class BaiduMapConfig implements Serializable {
        public boolean showMyLocation;//是否需要定位
        public boolean enableSearch;//是否允许用户搜索
        public boolean showDistance;//是否显示距离
        public boolean showOtherLocation;//是否显示其他人的位置信息
        public LocationDetails presetMyLocation;//预设的自己位置
        public LocationDetails otherLocation;//之前已经预设好的位置信息
        public boolean needLocationBack;//是否需要返回当前在地图上选择的位置信息
        /**
         * 是否显示路线规划
         */
        public boolean showRoute;

        public BaiduMapConfig(boolean showMyLocation, boolean enableSearch, boolean showDistance, boolean showOtherLocation, LocationDetails presetMyLocation, LocationDetails otherLocation, boolean needLocationBack) {
            this.showMyLocation = showMyLocation;
            this.enableSearch = enableSearch;
            this.showDistance = showDistance;
            this.showOtherLocation = showOtherLocation;
            this.presetMyLocation = presetMyLocation;
            this.otherLocation = otherLocation;
            this.needLocationBack = needLocationBack;
        }

        public BaiduMapConfig(boolean showMyLocation, boolean enableSearch, boolean showDistance, boolean showOtherLocation, LocationDetails presetMyLocation, LocationDetails otherLocation, boolean needLocationBack, boolean showRoute) {
            this.showMyLocation = showMyLocation;
            this.enableSearch = enableSearch;
            this.showDistance = showDistance;
            this.showOtherLocation = showOtherLocation;
            this.presetMyLocation = presetMyLocation;
            this.otherLocation = otherLocation;
            this.needLocationBack = needLocationBack;
            this.showRoute = showRoute;
        }
    }

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.fragment_map);
        Intent intent = getIntent();
        baiduMapConfig = (BaiduMapConfig) intent.getSerializableExtra(ActivityMap.BAIDUMAP_CONFIG);
        if (baiduMapConfig == null) {
            finish();
            return;
        }
        titleView = UIUtils.setTitle(this, R.color.white, R.color.black_0a, "地图定位");
        titleView.setBackFinish(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        titleView.setLeftIconRes(R.drawable.arrow_black);
        titleView.setRight("完成", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResultAndFinish();
            }
        });
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        baiduMap = mapView.getMap();
//        .setOnActivityDispatchTouchEventListener(new ActivityBase.OnActivityDispatchTouchEventListener() {
//            @Override
//            public boolean onActivityDispatchTouchEvent(MotionEvent ev) {
//                switch (ev.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        validateStatus = true;
//                        break;
//                }
//                int pointerCount = ev.getPointerCount();
//                if (pointerCount > 1) {
//                    validateStatus = false;
//                    if (null != baiduMap.getCameraPosition()) {
//                        zoom = baiduMap.getCameraPosition().zoom;
//                    }
//                }
//                return false;
//            }
//        });
        UiSettings uiSettings = baiduMap.getUiSettings();
        uiSettings.setAllGesturesEnabled(true);
        uiSettings.setZoomControlsEnabled(true);//缩放按钮
        uiSettings.setMyLocationButtonEnabled(false);//我的位置
        uiSettings.setCompassEnabled(true);//指南针
        uiSettings.setScaleControlsEnabled(false);//标尺
        uiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);

        baiduMap.setLocationSource(this);// 设置定位监听
        baiduMap.setMyLocationEnabled(true);
        baiduMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);

        // 设置地图POI点击事件
        baiduMap.setOnPOIClickListener(this);

        // 自定义系统定位小蓝点
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色

        locationView = (TextView) findViewById(R.id.locationView);
        locationView.setVisibility(View.INVISIBLE);
        baiduMap.setOnCameraChangeListener(this);

        mapViewContainer = findViewById(R.id.mapViewContainer);
        locationDisableView = findViewById(R.id.locationDisableView);
    }

    @Override
    public void initData() {

    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

}
